import 'package:flutter/material.dart';
import 'package:sqflite_demo/helpers/database_helper.dart';
import 'package:sqflite_demo/model/Chapter.dart';

import '../model/Book.dart';
import '../router/MyRouter.dart';
import '../widget/status_view.dart';

class Read extends StatefulWidget with RouterBridge<Book> {
  const Read({super.key});

  @override
  State<Read> createState() => _ReadState();
}

class _ReadState extends State<Read> {
  String chapterTitle = "阅读界面";

  int currentChapter = 0; // 章节编码
  int chapterCode = 0;
  String fileContent = ""; // 章节内容

  int bookId = 0;
  final db = DatabaseHelper();
  late List<Chapter> chapters = [];

  late ScrollController _scrollController;
  late final StatusViewController _controller;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController(); // 初始化 ScrollController 定位用的
    _controller = StatusViewController(); // 初始化 StatusViewController 视图控制器
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final book = widget.argumentOf(context); // 替换为实际获取逻辑
    bookId = book?.id ?? 0;
    _loadChapters();
  }

  Future<void> _loadChapters() async {
    setState(() {
      _controller.showLoading(); // 开始加载
    });
    try {
      final queryResult = await db.getChaptersByBookId(bookId);
      setState(() {
        chapters = queryResult.map((map) => Chapter.fromMap(map)).toList();
        if (chapters.isNotEmpty) {
          currentChapter = chapterCode; // 初始化到第一章
          fileContent = chapters[currentChapter].content ?? '默认值';
        }
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("加载章节失败: $e")),
      );
    } finally {
      setState(() {
        _controller.loaded(); // 加载完成
      });
    }
  }

  @override
  void dispose() {
    _scrollController.dispose(); // 确保在销毁时释放资源
    super.dispose();
  }

  void navigateToChapter(int index) {
    setState(() {
      currentChapter = index;
      chapterCode = currentChapter;
      fileContent = chapters[currentChapter].content ?? "章节内容为空";
      _scrollToTop();
    });
  }

  void nextPage() {
    if (currentChapter < chapters.length - 1) {
      navigateToChapter(currentChapter + 1);
      chapterCode = currentChapter;
    }
  }

  void prePage() {
    if (currentChapter > 0) {
      navigateToChapter(currentChapter - 1);
      chapterCode = currentChapter;
    }
  }

  bool _isScrolling = false;
  void _scrollToTop() async {
    if (_isScrolling) return; // 防止重复调用
    _isScrolling = true;

    await _scrollController.animateTo(
      0.0,
      duration: Duration(milliseconds: 30),
      curve: Curves.easeOut,
    );
    _isScrolling = false;
  }

  Widget _buildChild() => ListView(
    padding: EdgeInsets.zero,
    children: <Widget>[
      DrawerHeader(
        decoration: BoxDecoration(
          image: DecorationImage(
              image: AssetImage('assets/images/cover.png'),
              fit: BoxFit.cover),
        ),
        child: Text(
          '书籍目录',
          style: TextStyle(
            fontSize: 24,
            // 配置跟随主题
            color: Colors.white,
            shadows: [
              Shadow(
                color: Colors.black,
                offset: Offset(1, 1),
                blurRadius: 3,
              ),
            ],
          ),
        ),
      ),
      ..._buildMenuItems(),
    ],
  );

  List<Widget> _buildMenuItems() {
    // 太美妙了
    return chapters.map((item) {
      return ListTile(
        leading: Icon(Icons.book_outlined),
        title: Text(item.title),
        onTap: () {
          // 这样直接实现了item 与 index 的结合
          navigateToChapter(chapters.indexOf(item)); // 跳转到对应章节
        },
      );
    }).toList();
  }

  late bool _showAppBar = true; // 控制 AppBar 是否显示

  void _toggleAppBar() {
    setState(() {
      _showAppBar = !_showAppBar; // 切换 AppBar 显示状态
    });
  }


  bool viewMode = true;
  void showViewMenu(BuildContext context) {
    showMenu(
      context: context,
      position: RelativeRect.fromLTRB(
        100, // 根据需要调整位置（左边距）
        100, // 根据需要调整位置（上边距）
        0,   // 右边距
        0,   // 下边距
      ),
      items: [
        PopupMenuItem(
          value: 'scroll',
          child: Text('滑动显示'), // 菜单项1
        ),
        PopupMenuItem(
          value: 'page',
          child: Text('分页模式'), // 菜单项2，修正了描述
        ),
      ],
    ).then((value) {
      if (value != null) {
        if (value == 'scroll') {
          setState(() {
            viewMode = true; // 设置为滑动模式
          });
        } else if (value == 'page') {
          setState(() {
            viewMode = false; // 设置为页面模式
          });
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _showAppBar
          ? AppBar(
        toolbarHeight: 36,
        title: Text("$chapterTitle", style: TextStyle(fontSize: 16)),
        automaticallyImplyLeading: true,
        actions: [
          IconButton(onPressed: (){
            showViewMenu(context);
          }, icon: Icon(Icons.settings))
        ],
      )
          : null, // 根据 _showAppBar 决定是否显示 AppBar
      drawer: Drawer(
        elevation: 2,
        child: _buildChild(),
      ),
      body: GestureDetector(
        onTap: _toggleAppBar, // 点击页面时切换 AppBar 显示状态
        child: Column(
          children: [
            if(!_showAppBar)
              SizedBox(height: 50),
            if(viewMode) ...[
              Expanded(
                child: SingleChildScrollView(
                  controller: _scrollController,
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      children: [
                        Text(
                          chapters.isNotEmpty ? chapters[currentChapter].title : "章节加载中...",
                          style: TextStyle(fontSize: 20),
                        ),
                        Text(
                          fileContent.isEmpty ? "章节内容为空" : fileContent,
                          style: TextStyle(fontSize: 18),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            TextButton(
                              onPressed: currentChapter > 0 ? prePage : null,
                              child: Text("上一章节"),
                            ),
                            TextButton(
                              onPressed: currentChapter < (chapters.length) - 1 ? nextPage : null,
                              child: Text("下一章节"),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
              ),
            ] else ...[
              Text("这里是分页阅读"),
            ]
          ],
        ),
      ),
    );
  }
}